#!/bin/bash
set -e

echo "=============================================="
echo "HunyuanWorld-Mirror NPU API Service"
echo "=============================================="

echo "Checking HunyuanWorld-Mirror code..."
if [ -z "$(ls -A /app/HunyuanWorld-Mirror 2>/dev/null)" ]; then
    echo "Directory is empty, trying to clone from GitHub..."
    cd /app/HunyuanWorld-Mirror
    git clone https://github.com/Tencent-Hunyuan/HunyuanWorld-Mirror.git . || echo "Git clone failed, assuming code is mounted."
fi

# 应用 NPU 补丁
echo "Applying NPU patches..."
/app/patch_npu.sh || echo "Patch script not found or failed, continuing..."

echo "Checking NPU availability..."
python3 -c "import torch; import torch_npu; print(f'NPU Available: {torch.npu.is_available()}')" || echo "NPU check failed, will use CPU"

# 设置 Python 路径
export PYTHONPATH=/app/HunyuanWorld-Mirror:$PYTHONPATH

# 根据环境变量决定启动模式
START_MODE=${START_MODE:-"api"}

case $START_MODE in
    "api")
        echo "Starting REST API Service on port 8000..."
        python3 /app/api/main.py
        ;;
    "gradio")
        echo "Starting Gradio Demo..."
        cd /app/HunyuanWorld-Mirror
        if [ -f "app.py" ]; then
            python3 app.py
        else
            echo "Gradio app.py not found!"
            exit 1
        fi
        ;;
    "bash")
        echo "Starting interactive bash..."
        /bin/bash
        ;;
    *)
        echo "Unknown START_MODE: $START_MODE"
        echo "Valid options: api, gradio, bash"
        exit 1
        ;;
esac
